package com.sys.SysAI.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

@Service
public class SysAiWaterQualityService {

    private static final Logger log = LoggerFactory.getLogger(SysAiWaterQualityService.class);
    private static final ObjectMapper mapper = new ObjectMapper();

    @Value("${ollama.apiPath}")
    private String ollamaApiPath;

    @Value("${ollama.modelName}")
    private String ollamaModelName;

    /**
     * 对海马养殖水质进行分析，并返回优化建议
     * @param parameters 包含pH、溶解氧、氨氮等参数的Map
     * @return 模型返回的优化建议（结构化数据）
     */
    public Map<String, String> analyzeWaterQuality(Map<String, Object> parameters) {
        // 构造请求体
        Map<String, Object> task = new HashMap<>();
        task.put("model", ollamaModelName);
        task.put("stream", false);
        StringBuilder promptBuilder = new StringBuilder("你是一位专业的海洋生物养殖专家，请根据以下海马养殖水体的参数进行分析并给出详细优化建议，例如：PH低于正常值需要添加什么药剂来调整。" +
                "请严格按照JSON格式返回，包含三个字段：" +
                "\"waterStability\"（水质稳定性分析）、" +
                "\"seahorseHealth\"（海马健康影响分析）、" +
                "\"improvementSuggestions\"（改进建议），" +
                "每个字段的值为字符串，内容详实且不要包含任何markdown格式符号。水质参数如下：\n\n");

        for (Map.Entry<String, Object> entry : parameters.entrySet()) {
            promptBuilder.append(entry.getKey()).append(": ").append(entry.getValue()).append("\n");
        }

        task.put("prompt", promptBuilder.toString());

        // 设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        // 封装请求体和头
        HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(task, headers);

        // 发送 POST 请求并处理响应
        return parseStructuredResponse(sendRequest(requestEntity));
    }

    /**
     * 发送请求到Ollama API
     */
    private String sendRequest(HttpEntity<Map<String, Object>> requestEntity) {
        RestTemplate restTemplate = new RestTemplate();
        try {
            log.info("调用Ollama API: {}", ollamaApiPath);
            return restTemplate.postForObject(ollamaApiPath, requestEntity, String.class);
        } catch (RestClientException e) {
            log.error("调用Ollama API失败，URL: {}", ollamaApiPath, e);
            throw new RuntimeException("水质分析服务暂时不可用", e);
        }
    }

    /**
     * 解析API响应为结构化Map
     */
    private Map<String, String> parseStructuredResponse(String response) {
        try {
            log.info("Ollama API 原始响应: {}", response);

            // 提取模型返回的response字段内容
            JsonNode rootNode = mapper.readTree(response);
            String content = rootNode.path("response").asText().trim();

            // 清理可能的格式标记
            content = content.replaceAll("```json", "").replaceAll("```", "").trim();

            // 解析为结构化Map
            Map<String, String> resultMap = mapper.readValue(content,
                    mapper.getTypeFactory().constructMapType(HashMap.class, String.class, String.class));

            log.info("解析后的建议: {}", resultMap);
            return resultMap;

        } catch (JsonProcessingException e) {
            log.error("解析Ollama API响应失败，响应内容: {}", response, e);
            throw new RuntimeException("API响应格式错误", e);
        }
    }
}
